//
//  ConBaseSinglePayVc.m
//  Shengzhuli
//
//  Created by FXGuo on 2018/2/12.
//  Copyright © 2018年 kamangkeji. All rights reserved.
//

#import "ConBaseSinglePayVc.h"
#import "PayTypeTableViewCell.h"
#import "PayTool.h"
#import "NewPaySuccessVc.h"
#import "MBProgressHUD+MJ.h"
#import "PersonNetWork.h"
#import "SZLAccountHelper.h"
#import "NewHomeNetwork.h"
#import "ValibleTicketCell.h"
#import "NSDate+Extension.h"
#import "NewPaySuccessVc.h"

@interface ConBaseSinglePayVc ()<UITableViewDataSource,UITableViewDelegate,PayTypeTableViewCellDelegate>

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *tickets;
@property (nonatomic,assign) PayType payType;
@property (nonatomic,strong) PersonInfo *info;
@property (nonatomic,strong) SingleCreateModel *mySingleModel;
@property (nonatomic,strong) SingleCreateModel *requestModel;//从后台请求来的

@end

@implementation ConBaseSinglePayVc

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"收银台";
    self.payType = -1;
    [self getValibleTickets];
}
#pragma mark ----------table datasourece delegate------------
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    if (self.specialModel.count == 1) {
        return 1;
    }
    return self.tickets.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) return 280;
    return 90;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        PayTypeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([PayTypeTableViewCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
        cell.model = self.mySingleModel;
        cell.clipsToBounds = YES;
        return cell;
    }
    ValibleTicketCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ValibleTicketCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.tickets[indexPath.row];
    cell.selectTicketBlock = ^(TicketModel *model, BOOL isAdd) {
        if (isAdd) {
            [self.specialModel.tickets addObject:model];
        }else {
            [self.specialModel.tickets removeObject:model];
        }
        [self calculatePrice];
        PayTypeTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
        cell.model = self.mySingleModel;
    };
    return cell;
}
#pragma mark  ------------- 切换支付方式---------------
- (void)payTypeTableViewCellClick:(PayType)type
{
    self.payType = type;
}
#pragma mark -------------支付相关-----------------------
- (void)alipayTopay:(NSDictionary *)parame
{
    __WEAK
    [[PayTool shareTool] aplipayWithParame:parame callback:^() {
        [weakSelf jumpToSuccess];
    }];
}
- (void)weixinToPay:(NSDictionary *)parame
{
    __WEAK
    [[PayTool shareTool]weixinPayWithParame:parame callback:^{
        [weakSelf jumpToSuccess];
    }];
}
- (void)leftMoneyTopay:(NSDictionary *)parame
{
    if (self.info.balance<self.mySingleModel.sumPrice) {
        [MBProgressHUD showError:@"余额不足" toView:self.view];
        return;
    }
    __WEAK
    [[PayTool shareTool] leftMoneyWithParame:parame CallBack:^{
        [weakSelf jumpToSuccess];
    }];
}
//后台查询后的跳转
- (void)jumpToSuccess
{
    //    if (self.paySuccessBlock) {
    //        self.paySuccessBlock();
    //    }
    __WEAK
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NewPaySuccessVc *vc = [[NewPaySuccessVc alloc]init];
        vc.isFromBase = YES;
        [self.navigationController pushViewController:vc animated:YES];
    });
}
//获取用户可用券
- (void)getValibleTickets
{
    NSMutableDictionary *parames = [NSMutableDictionary dictionary];
    parames[@"token"] = [SZLAccountHelper shareInstance].token;
    parames[@"clubCommodityId"] = self.specialModel.ID;
    parames[@"clubId"] = @(self.clubModel.ID);
    if (self.activityId) {
        parames[@"activityId"] = @(self.activityId);
        parames[@"id"] = self.specialModel.ID;
    }
    [self showWaiter];
    [NewHomeNetwork getBaseValibleTicketWithParame:parames response:^(BOOL success, NSString *msg, NSArray *tickets) {
        [self.specialModel.tickets removeAllObjects];
        if (success) {
            [self.tickets addObjectsFromArray:tickets];
            [self getPersonInfo];
        }else {
            [self hideWaiter];
            [MBProgressHUD showError:msg];
        }
    }];
}
//主要获取账户余额
- (void)getPersonInfo
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    [PersonNetWork getPersonInfoWithParame:parame response:^(BOOL success, NSString *msg,NSString *errorCode,PersonInfo *info) {
        [self hideWaiter];
        if (success) {
            self.info = info;
            
            SingleCreateModel *model = [[SingleCreateModel alloc]init];
            model.sumPrice = self.specialModel.sumPrice;
            model.userAccountBalance = info.balance;
            self.mySingleModel = model;
            
            [self.view addSubview:self.tableView];
        }else{
            [self hideWaiter];
            [MBProgressHUD showError:msg toView:self.view];
        }
    }];
}
//去支付操作
- (void)payBtnClick
{
    if (self.mySingleModel.sumPrice != 0) {
        if ((self.payType!=PayTypeAlipay)&&(self.payType!=PayTypeWeixin)&&(self.payType!=PayTypeLeftMoney)) {
            [MBProgressHUD showError:@"请选择支付方式" toView:self.view];
            return;
        }
    }
    //1.创建订单
    NSMutableDictionary *parames = [NSMutableDictionary dictionary];
    parames[@"token"] = [SZLAccountHelper shareInstance].token;
    parames[@"clubCommodityId"] = self.specialModel.ID;
    parames[@"personNum"] = @(self.specialModel.count);
    NSDate *date = self.specialModel.timeArr[0];
    parames[@"startDate"] = [date convertDateToSting];
    parames[@"day"] = @(self.specialModel.maxDay);
    parames[@"price"] = @(self.mySingleModel.sumPrice);
    NSMutableArray *arr = [NSMutableArray array];
    for (TicketModel *model in self.specialModel.tickets) {
        [arr addObject:model.ticketNo];
    }
    parames[@"ticketNos"] = [arr componentsJoinedByString:@"#"];
    [self showWaiter];
    [NewHomeNetwork getCreateBaseSingleWithParame:parames response:^(BOOL success, NSString *msg,SingleCreateModel *model) {
        [self hideWaiter];
        if (success) {
            self.requestModel = model;
            if (model.sumPrice == 0) {//不用付钱直接跳成功
                NewPaySuccessVc *vc = [[NewPaySuccessVc alloc]init];
                vc.isFromBase = YES;
                vc.isZero = YES;
                [self.navigationController pushViewController:vc animated:YES];
            }else {
                [self singleTopay];
            }
        }else {
            [MBProgressHUD showError:msg];
        }
    }];
}
- (void)calculatePrice
{
    if (self.specialModel.tickets.count > 0) {
        NSInteger count = self.specialModel.count;
        BOOL isHaveSelf = NO;//记录是否有自己的券
        for (TicketModel *model in self.specialModel.tickets) {
            if ([model.ticketId isEqualToString:@"6"]) {//代表别人的
                if (isHaveSelf) {
                    if (model.num >= count) {
                        count = 0;
                    }else {
                        count -= model.num;
                    }
                }else {
                    if (model.num >= count-1) {
                        count = 1;
                    }else {
                        count -= model.num;
                    }
                }
            }else {//代表自己的
                count -= 1;
                isHaveSelf = YES;
            }
        }
        self.mySingleModel.sumPrice = self.specialModel.price * count;
    }else {
        self.mySingleModel.sumPrice = self.specialModel.price * self.specialModel.count;
    }
}
//掉起支付
- (void)singleTopay
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    parame[@"payNumber"] = self.requestModel.payNumber;
    switch (self.payType) {
        case PayTypeAlipay:
        {
            [self alipayTopay:parame];
        }
            break;
        case PayTypeWeixin:
        {
            [self weixinToPay:parame];
        }
            break;
        case PayTypeLeftMoney:
        {
            [self leftMoneyTopay:parame];
        }
            break;
        default:
            break;
    }
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = RGBColor(239, 239, 244);
        _tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([PayTypeTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([PayTypeTableViewCell class])];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ValibleTicketCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([ValibleTicketCell class])];
        UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, 60)];
        UIButton *payBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, 20, ScreenW-30, 40)];
        [payBtn setTitle:@"支付" forState:UIControlStateNormal];
        [payBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [payBtn setBackgroundImage:GetImage(@"btn_bg_login_normal") forState:UIControlStateNormal];
        [payBtn addTarget:self action:@selector(payBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [footerView addSubview:payBtn];
        _tableView.tableFooterView = footerView;
    }
    return _tableView;
}
- (NSMutableArray *)tickets
{
    if (!_tickets) {
        _tickets = [NSMutableArray array];
    }
    return _tickets;
}

@end
